package cn.edu.hqu.cst.android.fourthexperiment;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {
    Button bind,unbind,getServiceStatus;
    // 保持所启动的Service的IBinder对象
    BindService.MyBinder binder;

    // 定义一个ServiceConnection对象
    private ServiceConnection conn = new ServiceConnection(){
        // 当该Activity与Service连接成功时回调该方法
        @Override
        public void onServiceConnected(ComponentName name, IBinder service){
            System.out.println("--Service Connected--");
            binder = (BindService.MyBinder)service;
        }
        // 当该Activity与Service断开连接时回调该方法
        @Override
        public void onServiceDisconnected(ComponentName name){
            System.out.println("--Service Disconnected--");
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 获取程序界面中的start、stop、getServiceStatus按钮
        bind = (Button) findViewById(R.id.bind);
        unbind = (Button) findViewById(R.id.unbind);
        getServiceStatus = (Button) findViewById(R.id.getServiceStatus);

        //创建启动Service的Intent
        final Intent intent = new Intent(this,BindService.class);
        //为Intent设置Action属性
        intent.setAction("FourthExperiment.setAction");

        bind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bindService(intent,conn,BindService.BIND_AUTO_CREATE);
                Toast.makeText(MainActivity.this, "绑定成功！",Toast.LENGTH_LONG).show();
            }
        });

        unbind.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View source){
                //解除绑定Serivce
                unbindService(conn);
                Toast.makeText(MainActivity.this, "解绑成功！",Toast.LENGTH_LONG).show();
            }
        });

        getServiceStatus.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View source){
                // 获取、并显示Service的count值
                Toast.makeText(MainActivity.this, "Serivce的count值为：" + binder.getCount(), Toast.LENGTH_LONG).show();
            }
        });
    }
}
